﻿using System;

namespace theeg.GeometryWpf
{
    public class ComputationalCircle : ComputationalShape
    {
        public double CenterX, CenterY;

        public double Radius
        {
            get;
            private set;
        }

        private readonly double _radius2;


        public ComputationalCircle()
        {
        }

        public ComputationalCircle(double left, double top, double right, double bottom)
        {
            CenterX = (left + right) / 2;
            CenterY = (top + bottom) / 2;
            Radius = Math.Min(right - left, bottom - top) / 2;
            _radius2 = Radius * Radius;
            BoundingBox = new ComputationalRectangle(left, top, right, bottom);
        }

        public ComputationalCircle(double cx, double cy, double radius)
        {
            CenterX = cx;
            CenterY = cy;
            Radius = radius;
            _radius2 = Radius * Radius;
            BoundingBox = new ComputationalRectangle(CenterX - radius, CenterY - radius, CenterX + radius, CenterY + radius);
        }

        public override bool Contains(System.Windows.Point pt)
        {
            return Contains(pt.X, pt.Y);
        }

        public override bool Contains(double x, double y)
        {
            if (x < BoundingBox.L || x > BoundingBox.R || y < BoundingBox.T || y > BoundingBox.B)
            {
                //early reject through bounding box
                return false;
            }
            double dd = (CenterX - x) * (CenterX - x) + (CenterY - y) * (CenterY - y);
            return dd <= _radius2;
        }

        public override ShapeOverlapping Contains(ComputationalRectangle rect)
        {
            ShapeOverlapping boundsin = BoundingBox.Contains(rect);
            if (boundsin == ShapeOverlapping.Outside)
                return ShapeOverlapping.Outside;
            int count = 0;
            if (Contains(rect.L, rect.T)) count++;
            if (Contains(rect.L, rect.B)) count++;
            if (Contains(rect.R, rect.T)) count++;
            if (Contains(rect.R, rect.B)) count++;
            if (count == 4) return ShapeOverlapping.Contains;
            boundsin = rect.Contains(BoundingBox);
            if (count == 0 && boundsin == ShapeOverlapping.Outside)
                return ShapeOverlapping.Outside;
            return ShapeOverlapping.Intersects;
        }
    }
}
